#!/bin/bash
# simple test for simple pt
# needs to be run as root
# tester [sptcmd opts]
# issues:
# may need -k to finish
# some tests may need a quiescent system

set -e
set -x

failed() {
	echo FAILED
	exit 1
}
trap failed ERR 0

#export LD_LIBRARY_PATH=$(pwd)/../processor-trace/lib
export PATH=$PATH:.

./TEST-FTRACE

PREFIX=stest

EXTRA="-t $1 $2 $3"

STDCMD=loop
CMD=$STDCMD

run() {
	sptcmd $EXTRA -o $PREFIX "$@" taskset -c 0 $CMD
	$V sptdecode --sideband ${PREFIX}.sideband --pt ${PREFIX}.0 $DARGS > ${PREFIX}.out
}

gcc -o loop loop.c -g
run
grep -q  __libc_start_main.*main stest.out
grep -q page_fault stest.out
run -c loop
grep -q  __libc_start_main.*main stest.out
grep -q page_fault stest.out
run --disretc --no-user
grep -q page_fault stest.out
run --no-kernel -c loop
grep -q  __libc_start_main.*main stest.out
grep -v -q page_fault stest.out

# long trace test to fill the buffer
CMD=BC1s
run --no-kernel -c bc
CMD=$STDCMD
[ "$(stat -c %s stest.0)" -eq $[2048*1024] ]

# retest simple run
run --no-user
grep -q page_fault stest.out

# FIXME: work around libipt bug for now on this test case
if ! ./ptfeature cyc ; then
	run --start-addr SyS_prctl --stop-addr SyS_personality
	grep -q main stest.out
fi

MAIN=$(nm loop | awk '$3 == "main" { print "0x" $1 }  ')
FINI=$(nm loop | awk '$3 == "_fini" { print "0x" $1 }  ')

if ./ptfeature filter ; then
	run --filter $MAIN,$FINI -c loop
	grep -v -q write stest.out
fi

if ./ptfeature stop ; then
	run --stop-range $MAIN,$FINI -K -c loop
	grep -q __libc_start_main stest.out
	grep -v -q -w main stest.out # main is not reached
	# XXX check for disabled message later
fi

if ./ptfeature cyc psb mtc ; then
	run --cyc 1 --mtc 1 --psb 1
	grep -q main stest.out
fi

# simple dwarf resolving test
cp loop loop2
cp loop loop3
cp loop loop4
gcc -I/usr/include/libdwarf -I/usr/local/include/libdwarf -g -o dwarf dwarf.c -DTEST=1 -g -ldwarf -lelf
dwarf loop:$MAIN loop2:$MAIN loop3:$MAIN loop4:$MAIN
rm loop2 loop3 loop4 dwarf

set +x
trap "" ERR 0

echo 
echo SUCCEEDED
echo



